/**
 * Created by Nie on 2015/12/10.
 */
app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
    $routeProvider.
    when('/company/home', {
        templateUrl: 'home/company_home.html',
        controller: 'companyHomeController'
    })
}]);
function companyHomeService($http, $location) {
    return {
        servantlist : function(data ,limit,page,app_id, fn ){
            var param = {
                limit: limit,
                page: page,
                name : (data != ''&& data != undefined)?data.username:'',
                identify : (data != ''&& data != undefined)?data.identify:'',
                address : (data != ''&& data != undefined)?data.address:'',
                telephone : (data != ''&& data != undefined)?data.telephone:'',
                nativePlace : (data != ''&& data != undefined)?data.nativePlace:'',
                from : (data != ''&& data != undefined)?data.from:'',
                sex : (data != ''&& data != undefined)?data.sex:'',
                cers : (data != ''&& data != undefined)?data.cers:'',
                technique : (data != ''&& data != undefined)?data.technique:'',
                service : (data != ''&& data != undefined)?data.service:'',
                servantstatus : (data != ''&& data != undefined)?data.servantstatus:'',
                verifystatus : (data != ''&& data != undefined)?data.verifystatus:''
            };
            baas_jz.call({
                'http': $http,
                'method': 'post',
                // 'uri': 'servant/servant/list',
                'uri': 'servant/servant/search',
                'data': param,
                'success': function(d) {
                    if( typeof fn == 'function'){
                        fn( d);
                    }
                }
            });
        }
        ,orderlist: function(data,limit, page, app_id, fn) {
            var param = {
                limit: limit,
                page: page,
                start_time:(data != ''&& data != undefined)?data.start_time:'',
                end_time:(data != ''&& data != undefined)?data.end_time:'',
                company:(data != ''&& data != undefined)?data.company:'',
                status:(data != ''&& data != undefined)?data.status:'',
                score:(data != ''&& data != undefined)?parseInt(data.score):'',
                serviceType1:(data != ''&& data != undefined && data.serviceType1!=undefined)?data.serviceType1:'',
                serviceType2:(data != ''&& data != undefined && data.serviceType2!=undefined)?data.serviceType2:'',
                selected_manager_group_id : (data != ''&& data != undefined && data.selected_manager_group_id!=undefined)?data.selected_manager_group_id:'',
                selected_company_code :(data != ''&& data != undefined && data.selected_company_code!=undefined)?data.selected_company_code:'',
                //serviceType3:(data != ''&& data != undefined && data.serviceType3!=undefined)?data.serviceType3:'',
                order_id:(data != ''&& data != undefined)?data.order_id:'',
                name:(data != ''&& data != undefined)?data.username:'',
                address:(data != ''&& data != undefined)?data.address:'',
                phone:(data != ''&& data != undefined)?data.phone:''
            };
            if(data != ''&& data != undefined && data.serviceType3!=undefined)
                param.serviceType3 = data.serviceType3;
            baas_jz.call({
                'http': $http,
                'method': 'post',
                'uri': 'order/orderList/count',
                'data' : param,
                'success': function(d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        },servantList: function(data, fn) {
            baas_jz.call({
                'http': $http,
                'method': 'get',
                'uri': 'servant/servant/list',
                'success': function(d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }

                }
            });
        }
        ,ordersCount: function( group,app_id, fn) {
            var param = {
                group: group
            };
            baas_jz.call({
                'http': $http,
                'method': 'get',
                'uri': 'order/order/statistics',
                'data' : param,
                'success': function(d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        }
        ,yuecount : function(start_date,company_code,app_id,fn){
            var param = {
                year: start_date,
                selected_company_code :(typeof company_code != undefined && company_code != '')?company_code:undefined
            };
            baas_jz.call({
                'http' : $http,
                'method' : 'get',
                'uri' : 'order/order/year/order/count',
                'data' : param,
                'success' : function(d){
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        }
        ,moneycount : function(start_date,app_id,fn){
            var param = {
                selected_company_code: (typeof start_date != undefined && start_date != '')?start_date:undefined
            };
            baas_jz.call({
                'http' : $http,
                'method' : 'get',
                'uri' : 'order/order/month/revenue/count',
                'data' : param,
                'success' : function(d){
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        }
        ,amountCount : function(amountData,app_id,fn){
            var param = {
                selected_manager_group_id : (typeof amountData != 'undefined'&& amountData != ''  && typeof amountData.selected_manager_group_id!='undefined')?amountData.selected_manager_group_id:'',
                selected_company_code :(typeof amountData != 'undefined'&& amountData != ''  && typeof amountData.selected_company_code!='undefined')?amountData.selected_company_code:''
            };
            baas_jz.call({
                'http' : $http,
                'method' : 'get',
                'data' : param,
                'uri' : 'order/orderList/total/revenue',
                'success' : function(d){
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        }
    };
}

app.factory('companyHomeService', ['$http', '$location', companyHomeService]);
app.controller('companyHomeController', ['$scope', '$routeParams', '$window', '$location', '$http', 'companyHomeService','cmsService', companyHomeController]);

function companyHomeController($scope, $window, $location, $http, $routeParams, companyHomeService,cmsService) {
    //服务人员
    $scope.servantList = function(){
        companyHomeService.servantlist( $scope.search,$scope.limit,$scope.selectedPage,$scope.app_id, function( json ){
            //console.log(json);
            $scope.list = json.list;
            $scope.servantCount = json.count;
        });
    };
    $scope.servantList();
    //订单数量&抢单

    $scope.orderList = function(){
        $scope.selectedPage = 1;
        $scope.limit = 5;
        $scope.search={
            status:""
        };
        var manager=JSON.parse(localStorage.getItem(sessionStorage.getItem("who")+"manager"));
        if(manager!=undefined && manager!=""){
            $scope.search.selected_company_code=manager.company_code;
        }
        if(manager!=undefined&&manager.isPension){
            $scope.search.selected_manager_group_id=manager.manager_group_id;
        }
        companyHomeService.orderlist($scope.search,$scope.limit, $scope.selectedPage, $scope.app_id, function(json) {
            $scope.lists = json['list'];
            $scope.orderCount = json['count'];
            $scope.currentPage = 1;
            //$scope.getPage(json['count']);
            //	console.log(json.list.length);
        });
    }
    $scope.orderList();
    //
    $scope.getServantList = function() {
        companyHomeService.servantList($scope.search,function(d){
            $scope.servantList=d["list"];
            for(i=0;i<$scope.servantList.length;i++){
                servant= $scope.servantList[i];
                if(servant["name"].length>0){
                    name=servant["name"];
                    servant["group"]=pinyin.getFullChars(name).substr(0,1);
                }
                $scope.servantList[i]=servant;
            }
        });
    };

    $scope.getServantList();
    $scope.grab=function(order_id,servant_id){
        if(servant_id==""){
            alert("请选择服务人员");
        }else{
            baas_jz.call({
                'http': $http,
                'method': 'post',
                'uri': 'order/order/grab/'+order_id+'/' + servant_id ,
                'success': function(d) {
                    console.log(d);
                    if(d.status==1){
                        alert("恭喜，抢单成功！");
                        $scope.orderList();
                    }
                }
            });
        }
    };
    $scope.serviceTypeCount = function(){
        companyHomeService.ordersCount("serviceType3_title",$scope.app_id,function(json){

            var af=0;
            var b=0;
            var c=0;
            var dataDonut = new Array();
            for(var i=0;i<json.res.retval.length;i++){
                var a=json.res.retval[i]['rate'];
                if(a!=null&&a!=""&& typeof a!="undefined"&& parseInt(a.substr(0, a.length-1))>3){
                    var title=json.res.retval[i]['serviceType3_title'];
                    if(title!=null)
                    {
                        dataDonut.push({});
                        dataDonut[af]['label'] = json.res.retval[i]['serviceType3_title'];
                        dataDonut[af]['data'] = json.res.retval[i]['count'];
                        af++;
                        b=b+parseInt(json.res.retval[i]['count']);
                        c=c+parseInt(a.substr(0, a.length-1));
                    }
                }
            }


            var d=(b/(c/100))-b;
            dataDonut.push({});

            dataDonut[af]['label'] = "其他";
            dataDonut[af]['data'] = d;


            $.plot('#graph-flot-donut', dataDonut, {
                series: {
                    pie: {
                        show: true,
                        innerRadius: 0.5,
                        label: {
                            show: true
                        }
                    }
                },
                colors: ['#e74c3c', '#f1c40f', '#2ecc71', '#3498db', '#9b59b6', '#95a5a6'],
                legend: {
                    show: false
                }
            });
        });
    };
    $scope.serviceTypeCount();

    $scope.statusTypeCount = function(){
        companyHomeService.ordersCount("status",$scope.app_id,function(json){
            var af=0;
            var b=0;
            var c=0;
            var dataDonut = new Array();
            for(var i=0;i<json.res.retval.length;i++){
                var a=json.res.retval[i]['rate'];
                console.log("==="+a);
                if(a!=null&&a!=""&& typeof a!="undefined"&& parseInt(a.substr(0, a.length-1))>5){
                    var title=json.res.retval[i]['status'];
                    if(title!=null&&title!="已删除")
                    {
                        dataDonut.push({});
                        dataDonut[af]['label'] = json.res.retval[i]['status'];;
                        dataDonut[af]['data'] = json.res.retval[i]['count'];
                        af++;
                        b=b+parseInt(json.res.retval[i]['count']);
                        c=c+parseInt(a.substr(0, a.length-1));
                    }
                }
            }

            var d=(b/(c/100))-b;
            dataDonut.push({});

            dataDonut[af]['label'] = "其他";
            dataDonut[af]['data'] = d;
            $.plot('#graph-flot-donuts', dataDonut, {
                series: {
                    pie: {
                        show: true,
                        innerRadius: 0.5,
                        label: {
                            show: true
                        }
                    }
                },
                colors: ['#e74c3c', '#f1c40f', '#2ecc71', '#3498db', '#9b59b6', '#95a5a6'],
                legend: {
                    show: false
                }
            });
        });
    };
    $scope.statusTypeCount();
    //收入统计
    $scope.amountCount = function(){
        var manager=JSON.parse(localStorage.getItem(sessionStorage.getItem("who")+"manager"));
        var amountData = {};
        if(typeof manager!='undefined' && manager!=""){
            amountData.selected_company_code=manager.company_code;
        }
        if(typeof manager!='undefined'&&manager.isPension){
            amountData.selected_manager_group_id=manager.manager_group_id;
        }
        companyHomeService.amountCount(amountData,$scope.app_id, function(json) {
            $scope.totalCount = json['total'];
        });
    }
    $scope.amountCount();

    $scope.yuecount = function(){
        var myDate = new Date();
        var year = myDate.getFullYear();
        var month = myDate.getMonth() + 1;
        var start_date = year;
        var manager=JSON.parse(localStorage.getItem(sessionStorage.getItem("who")+"manager"));
        var company_code;
        if(manager!=undefined && manager!=""){
            company_code = manager.company_code;
        }
        companyHomeService.yuecount(start_date,company_code,$scope.app_id,function(json){
            $scope.listCounts = json;

            console.log(json.result[11]);
            var likes = new Array(12);
            for(var j=0;j<12;j++){
                likes[j] = [j+1,json.result[j+1]];
            }

            var plot = $.plot($("#graph-flot-points"),
                [ { data: likes, label: "当月订单数量统计"} ], {
                    series: {
                        lines: {
                            show: true,
                            lineWidth: 2,
                            fill: true,
                            fillColor: { colors: [ { opacity: 0.3 }, { opacity: 0.3 } ] }
                        },
                        points: { show: true,
                            lineWidth: 2
                        },
                        shadowSize: 0
                    },
                    grid: { hoverable: true,
                        clickable: true,
                        tickColor: "#f9f9f9",
                        borderWidth: 0
                    },
                    colors: ["#e74c3c"],
                    xaxis: {ticks:10, tickDecimals: 0},
                    yaxis: {ticks:5, tickDecimals: 0},
                });

            function showTooltip(x, y, contents) {
                $('<div id="tooltip">' + contents + '</div>').css( {
                    position: 'absolute',
                    display: 'none',
                    top: y + 5,
                    left: x + 5,
                    border: '1px solid #fdd',
                    padding: '2px',
                    'background-color': '#dfeffc',
                    opacity: 0.80
                }).appendTo("body").fadeIn(200);
            }

            var previousPoint = null;
            $("#graph-flot-points").bind("plothover", function (event, pos, item) {
                $("#x").text(pos.x.toFixed(2));
                $("#y").text(pos.y.toFixed(2));

                if (item) {
                    if (previousPoint != item.dataIndex) {
                        previousPoint = item.dataIndex;

                        $("#tooltip").remove();
                        var x = item.datapoint[0].toFixed(0),
                            y = item.datapoint[1].toFixed(0);

                        showTooltip(item.pageX, item.pageY,
                            "当月订单数量" + " ： " + y);
                    }
                }
                else {
                    $("#tooltip").remove();
                    previousPoint = null;
                }
            });
            console.log(json);
        });
    };
    $scope.yuecount();

    $scope.moneyCount = function(){

        //收入
        if ($('#graph-bar').length) {

            var manager=JSON.parse(localStorage.getItem(sessionStorage.getItem("who")+"manager"));
            var company_code;
            if(manager!=undefined && manager!=""){
                company_code = manager.company_code;
            }

            companyHomeService.moneycount(company_code,$scope.app_id,function(json){

                $scope.listCounts = json;
                //console.log(json);
                var likes = new Array(31);
                for(var j=0;j<31;j++){
                    likes[j] = [j+1,0];
                }

                var db1 = [];
                console.log("test==="+json.res.retval.length);
                for (var i=0;i<json.res.retval.length;i++) {

                    console.log("i----"+i+'--count---'+(json.res.retval[i].total));
                    db1.push([i+1, parseInt((json.res.retval[i].total))]);
                }

                var series = new Array();
                series.push({
                    data : db1,
                    bars : {
                        show : true,
                        barWidth : 0.2,
                        order : 1,
                        lineWidth: 1,
                        fill: 1
                    }
                });
                $.plot("#graph-bar", series, {
                    colors: ['#2ecc71'],
                    grid: {
                        tickColor: "#ddd",
                        borderWidth: 0
                    },
                    shadowSize: 0
                });



            });

        };
    };
    $scope.moneyCount();



    //获取备忘录

    $scope.queryCms=function(){
        var search = {
            limit:10,
            page:1
        };
        var manager=JSON.parse(localStorage.getItem(sessionStorage.getItem("who")+"manager"));
        search.username=manager.manager_account;
        cmsService.list(search, function( json ){
            $scope.cmsList = json.list;

        });

    }
    $scope.queryCms();

}